﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data;
using System.Data.SqlClient;
using MyLib.MyConnect.MSSQL;
using MyLib.MyUtility;
using System.Web;

using System.Runtime.Serialization;
using System.Runtime.Serialization.Json;
using System.IO;
using System.Net;
namespace MyChocCuoi.DB.Member
{

    /// <summary>
    /// Thông tin lấy được tự facebook
    /// </summary>
    [DataContract]
    public class FacebookInfo
    {
        private static DataContractJsonSerializer jsonSerializer = new DataContractJsonSerializer(typeof(FacebookInfo));

        [DataMember(Name = "id")]
        public string ID { get; set; }

        [DataMember(Name = "email")]
        public string Email { get; set; }

        [DataMember(Name = "gender")]
        public string Gender { get; set; }

        [DataMember(Name = "name")]
        public string Name { get; set; }

        [DataMember(Name = "first_name")]
        public string FirstName { get; set; }

        [DataMember(Name = "last_name")]
        public string LastName { get; set; }

        [DataMember(Name = "link")]
        public string Link { get; set; }

        [DataMember(Name = "birthday")]
        public string Birthday { get; set; }

        [DataMember(Name = "locale")]
        public string Locale { get; set; }
        public static FacebookInfo Deserialize(string json)
        {
            if (string.IsNullOrEmpty(json))
            {
                throw new ArgumentNullException("json");
            }

            return Deserialize(new MemoryStream(Encoding.UTF8.GetBytes(json)));
        }

        public static FacebookInfo Deserialize(Stream jsonStream)
        {
            if (jsonStream == null)
            {
                throw new ArgumentNullException("jsonStream");
            }

            return (FacebookInfo)jsonSerializer.ReadObject(jsonStream);
        }

        public bool IsNull
        {
            get
            {
                if (string.IsNullOrEmpty(ID))
                    return true;
                else
                    return false;
            }
        }
    }

    public class MemberObject
    {
        public int MemberID = 0;
        public string OpenID = string.Empty;
        public string MemberName = string.Empty;
        public string Email = string.Empty;
        public string Image = string.Empty;
        public string OpenLink = string.Empty;
        public string Location = string.Empty;

        public int DieCount = 0;
        public int ViewCount = 0;
        public int CommentCount = 0;
        public int ShareCount = 0;
        public int LikeCount = 0;
        public int FunnyCount = 0;

        public int SexID = 0;

        public DateTime CreateDate = DateTime.MinValue;

        public int StatusID = 0;

        public bool IsNull
        {
            get
            {
                if (MemberID <= 0 && string.IsNullOrEmpty(OpenID))
                    return true;
                else
                    return false;
            }
        }

         public MemberObject()
        {

        }
        public static MemberObject Convert(DataTable mTable)
        {
            List<MemberObject> mList = new List<MemberObject>();
            mList = MyConvert.ConvertTable2Object<MemberObject>(mTable);
            if(mList.Count > 0)
            {
                return mList[0];
            }
            return new MemberObject();
        }
        public string GetImage()
        {
            return "/u/mem/" + this.MemberID.ToString() + ".png";
        }
       
        public string GetLink()
        {
            return MyConfig.Domain+"/u/mem/" + this.MemberID.ToString() + ".png";
        }
        public static string GetImagePath(int mMemberID)
        {
            return "/u/mem/" + mMemberID.ToString() + ".png";
        }
    }

    /// <summary>
    /// Thành viên quản trị
    /// </summary>
    public class Member
    {
        public enum Sex
        {
            Nothing = 0,
            Male = 1,
            Female = 2
        }
        public enum Status
        {
            Nothing = 0,
            Active = 1,
            Deactive = 2,
        }

        MyExecuteData mExec = new MyExecuteData();
        MyGetData mGet = new MyGetData();



        /// <summary>
        /// Tạo 1 Dataset mẫu
        /// </summary>
        /// <returns></returns>
        public DataSet CreateDataSet()
        {
            try
            {
                string[] mPara = { "Type" };
                string[] mValue = { "0" };
                DataSet mSet = mGet.GetDataSet("Sp_Member_Select", mPara, mValue);

                if (mSet != null && mSet.Tables.Count >= 1)
                {
                    mSet.DataSetName = "Parent";
                    mSet.Tables[0].TableName = "Child";
                }
                return mSet;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        public MemberObject Sync(FacebookInfo mInfo)
        {
            try
            {
                MemberObject mObject = new MemberObject();

                //Thực thi Store
                DataTable mTable = Select(4, mInfo.ID);

                if (mTable.Rows.Count > 0)
                {
                    List<MemberObject> mList = MyConvert.ConvertTable2Object<MemberObject>(mTable);
                    if (mList.Count > 0)
                        mObject = mList[0];

                }
                else
                {
                    //Insert vào db với thông tin từ facebook
                    #region MyRegion

                    mObject.OpenID = mInfo.ID;
                    mObject.Email = mInfo.Email;
                    mObject.MemberName = mInfo.Name;
                  
                    mObject.StatusID = (int)Status.Active;
                    mObject.CreateDate = DateTime.Now;
                    mObject.Location = mInfo.Locale;
                    mObject.OpenLink = mInfo.Link;
                    //Lưu file ảnh avatar
                    
                    if (mInfo.Gender.Equals("male", StringComparison.CurrentCultureIgnoreCase))
                    {
                        mObject.SexID = (int)Sex.Male;
                    }
                    else
                    {
                        mObject.SexID = (int)Sex.Female;
                    }
                    List<MemberObject> mList = new List<MemberObject>();
                    mList.Add(mObject);

                    DataSet mSet = new DataSet("Parent");
                    DataTable mTable_New = MyConvert.ConvertObject2Table(mList);
                    mTable_New.TableName = "Child";

                    mSet.Tables.Add(mTable_New);

                    MyConvert.ConvertDateColumnToStringColumn(ref mSet);

                    if (Insert(1, mSet.GetXml()))
                    {
                        mTable = Select(4, mInfo.ID);
                        if (mTable.Rows.Count > 0)
                        {
                            //Lấy memberID
                            mObject.MemberID = (int)mTable.Rows[0]["MemberID"];

                            mObject.Image = "/u/mem/" + mObject.MemberID.ToString() + ".png";

                            MyFile.SaveFileFromURL("https://graph.facebook.com/" + mInfo.ID + "/picture?width=200&height=200", MyFile.GetFullPathFile("~" + mObject.Image));
                    
                        }
                    }
                    #endregion
                }
                return mObject;
            }
            catch (SqlException ex)
            {
                throw ex;
            }
        }


        /// <summary>
        /// 
        /// </summary>
        /// <param name="Type">
        /// <para>Type = 0: Lấy dữ liệu mẫu</para>
        /// <para>Type = 1: Lấy chi tiết 1 Record (Para_1 = MemberID)</para>
        /// <para>Type = 2: Lay theo nhom thanh vien</para>
        /// </param>
        /// <param name="Para_1"></param>
        /// <returns></returns>
        public DataTable Select(int? Type, string Para_1)
        {
            try
            {
                string[] mpara = { "Type", "Para_1" };
                string[] mValue = { Type.ToString(), Para_1 };
                return mGet.GetDataTable("Sp_Member_Select", mpara, mValue);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="Type">Type = 0</param>
        /// <param name="XMLContent"></param>
        /// <returns></returns>
        public bool Update(int Type, string XMLContent)
        {
            try
            {
                string[] mpara = { "Type", "XMLContent" };
                string[] mValue = { Type.ToString(), XMLContent };
                if (mExec.ExecProcedure("Sp_Member_Update", mpara, mValue) > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }

            }
            catch (SqlException ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// Insert dữ liệu và trả về 1 table cần lấy sau khi insert
        /// </summary>
        /// <param name="Type">Type = 0: Insert full
        /// <para>Type = 1: Insert với thông tin từ facebook</para>
        /// </param>
        /// 
        /// <param name="XMLContent"></param>
        /// <returns></returns>
        public bool Insert(int Type, string XMLContent)
        {
            try
            {
                string[] mpara = { "Type", "XMLContent" };
                string[] mValue = { Type.ToString(), XMLContent };

                if (mExec.ExecProcedure("Sp_Member_Insert", mpara, mValue) > 0)
                {
                    return true;
                }
                else
                {
                    return false;
                }
            }
            catch (SqlException ex)
            {
                throw ex;
            }
        }



        public bool Delete(int Type, string XMLContent)
        {
            try
            {
                string[] mpara = { "Type", "XMLContent" };
                string[] mValue = { Type.ToString(), XMLContent };
                if (mExec.ExecProcedure("Sp_Member_Delete", mpara, mValue) > 0)
                {
                    return true;

                }
                else
                {
                    return false;
                }
            }
            catch (SqlException ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// Lấy tổng số dòng
        /// </summary>
        /// <returns></returns>
        public int TotalRow(int? Type, int? MemberGroupID, string SearchContent, string OrderBy, bool? IsActive)
        {
            try
            {
                string[] mPara = { "Type", "MemberGroupID", "SearchContent", "OrderBy", "IsActive", "IsTotalRow" };
                string[] mValue = { Type.ToString(), MemberGroupID.ToString(), SearchContent, OrderBy, (IsActive == null ? null : IsActive.ToString()), true.ToString() };

                return (int)mGet.GetExecuteScalar("Sp_Member_Search", mPara, mValue);

            }
            catch (SqlException ex)
            {
                throw ex;
            }
        }

        /// <summary>
        /// Lấy dữ liệu về phân trang
        /// </summary>
        /// <param name="Type">Type =1: Lấy dữ liệu về phân trang</param>
        /// <param name="MemberGroupID"></param>
        /// <param name="SearchContent"></param>
        /// <param name="OrderBy"></param>
        /// <param name="IsActive"></param>
        /// <returns></returns>
        public DataTable Search(int? Type, int BeginRow, int EndRow, int? MemberGroupID, string SearchContent, string OrderBy, bool? IsActive)
        {
            try
            {
                string[] mpara = { "Type", "BeginRow", "EndRow", "MemberGroupID", "SearchContent", "OrderBy", "IsActive", "IsTotalRow" };
                string[] mValue = { Type.ToString(), BeginRow.ToString(), EndRow.ToString(), MemberGroupID.ToString(), SearchContent, OrderBy, (IsActive == null ? null : IsActive.ToString()), false.ToString() };
                return mGet.GetDataTable("Sp_Member_Search", mpara, mValue);
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }

    }
}
